package cn.qiguai.sphapi.controller;

import cn.qiguai.sphapi.controller.request.PageSearchGoodsParam;
import cn.qiguai.sphapi.controller.response.Status;
import cn.qiguai.sphapi.controller.response.Result;
import cn.qiguai.sphapi.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Positive;
import java.util.Optional;

@RestController
@RequestMapping("/api/goods")
@Validated
public class GoodsController {
	@Autowired
	private GoodsService goodsService;

	@GetMapping("/getCategoryList")
	public Result getCategoryList() {
		return Optional
				.of(goodsService.getCategoryList())
				.map(list -> Result
						.builder()
						.code(Status.SELECT_OK.getCode())
						.msg(Status.SELECT_OK.getMsg())
						.data(list)
						.build())
				.orElse(Result.builder().build());
	}

	@PostMapping("/pageSearchGoods")
	public Result pageSearchGoods(@RequestBody PageSearchGoodsParam param) {
		return Optional
				.of(goodsService.pageSearchGoods(param))
				.map(page -> Result
						.builder()
						.code(Status.SELECT_OK.getCode())
						.msg(Status.SELECT_OK.getMsg())
						.data(page)
						.build())
				.orElse(Result.builder().build());
	}

	@PostMapping("/getCategoryAttrs")
	public Result getCategoryAttrs(Integer categoryId, String keyword) {
		return Optional
				.ofNullable(goodsService.getCategoryAttrs(categoryId, keyword))
				.map(list -> Result
						.builder()
						.code(Status.SELECT_OK.getCode())
						.msg(Status.SELECT_OK.getMsg())
						.data(list)
						.build())
				.orElse(Result.builder().build());
	}

	@GetMapping("/getGoodsInfo/{goodsId}")
	public Result getGoodsInfo(@PathVariable @Positive int goodsId) {
		return Optional
				.of(goodsService.getGoodsInfo(goodsId))
				.map(goods -> Result
						.builder()
						.code(Status.SELECT_OK.getCode())
						.msg(Status.SELECT_OK.getMsg())
						.data(goods)
						.build())
				.orElse(Result.builder().build());
	}
}
